package com.grant.HelloWorld.server;

import java.io.File;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.DeferredFileOutputStream;
import com.google.gwt.core.client.GWT;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class UploadServletOld extends HttpServlet {
	@Override
	protected void doPost(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) 
			throws javax.servlet.ServletException ,java.io.IOException {
		 String txt = "";
		 PrintWriter out = resp.getWriter();
/*		// Use "out" to send content to browser
		resp.setContentType("text/html");
	    
	    GWT.log("req content size ="+ req.getContentLength());
	    FileItem item = getFileItem(req);
	   
	    System.out.print("req content size ="+ req.getContentLength());
	    if (item!=null){
	    	GWT.log(item.getName()+ item.getSize()+ item.getContentType());
	    	byte buf[] = new byte[2000];
	    	int len = item.getInputStream().read(buf);
	    	for (int i=0;i<len;i++)
	    	txt = txt + String.valueOf(buf[i]);
	    }*/
	    
	    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
	                                        "Transitional//EN\">\n" +
	                "<HTML>\n" +
	                "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" +
	                "<BODY>\n" +
	                "<H1>Hello WWW</H1>\n" +
	                greetServer("") + 	
	                txt + 
	                "</BODY></HTML>");
	    log("greetServer(\"\")");
	};
	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		

		String serverInfo = getServletContext().getServerInfo();
		//String userAgent = getThreadLocalRequest().getHeader("User-Agent");

		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);
		//userAgent = escapeHtml(userAgent);

		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + "userAgent";
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
	
	  private FileItem getFileItem(HttpServletRequest request){ 
		// Create a factory for disk-based file items
		  FileItemFactory factory = new DiskFileItemFactory();

		  // Create a new file upload handler
		  ServletFileUpload upload = new ServletFileUpload(factory);

		  // Parse the request
		  try {
			  GWT.log("parse ... ");System.out.println("parse ... ");
			List /* FileItem */ items = upload.parseRequest(request);
			GWT.log(String.format("items size %d", items.size()));
			System.out.println(String.format("items size %d", items.size()));
			
			@SuppressWarnings("rawtypes")
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
			    FileItem item = (FileItem) iter.next();

			    if (!item.isFormField())  {
			        processUploadedFile(item);
			    }
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		  
		  return null;
  } 

	private void processUploadedFile(FileItem item){
		
	// Process a file upload
/*	  if (!item.isFormField()) {
	      String fieldName = item.getFieldName();
	      String fileName = item.getName();
	      String contentType = item.getContentType();
	      boolean isInMemory = item.isInMemory();
	      long sizeInBytes = item.getSize();
	      
	      System.out.println("fileName="+fileName);
	      System.out.println("sizeInBytes"+ new Long(sizeInBytes).toString());
	      File uploadedFile = new File("a.txt");
	      try {
			item.write(uploadedFile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	  }	 */
	  }

}
